(function ($) {
    window.onload = function () {
        //如果不是编辑界面，那么就不执行下面的操作
        var is_list_view = true;
        if (window.location.pathname == '/storage/level/') {
            var count = 0;
            var total = 0;
            var filesInfo = [];
            showLevels();
        } else {
            is_list_view = false;
            var old_name = '';
            $('#id_name').after('<input type="file" id="upload_file" name="file" multiple="multiple"/>') //插入按钮
            $('#upload_file').css("marginLeft", "8px")
            $('#upload_file').change({ type: "files" }, handleFileSelect);

            $('#id_name').attr("disabled", true);
            $('.submit-row').click(beforeSubmit);
        }

        class Info {
            constructor(name) {
                this.name = name;
                this.image = null;
                this.ios = null;
                this.android = null;

                this.image_url = '';
                this.ios_url = '';
                this.android_url = '';

                this.image_md5 = '';
                this.ios_md5 = '';
                this.android_md5 = '';
            }
            isFill() {
                if (this.image != null && this.ios != null && this.android != null) {
                    return true;
                } else {
                    return false;
                }
            }
            isUploadFill() {
                if (this.image_url != '' && this.ios_url != '' && this.android_url != '') {
                    return true;
                } else {
                    return false;
                }
            }
        }

        //初始化
        firebase.initializeApp(config);

        var auth = firebase.auth();
        var storageRef = firebase.storage().ref();

        auth.onAuthStateChanged(function (user) {
            if (user) {
                console.log('Anonymous user signed-in.', user);
                let upload_file = document.getElementById('upload_file');
                if (upload_file) {
                    upload_file.disabled = false;
                }
            } else {
                console.log('There was no anonymous session. Creating a new anonymous user.');
                auth.signInAnonymously();
            }
        });

        function beforeSubmit(evt) {
            $('#id_name').attr("disabled", false);
        }

        function showLevels() {
            $('#content-main').after('<div id="my_container" class="flex"><input type="file" id="upload_file" name="file" multiple="multiple"/>' +
                '<label id="process"></label></div>')
            $('#upload_file').css('float', 'left')
            $('#upload_file').change(handleBatchSelect);
            document.getElementById('upload_file').disabled = true;
        }

        function handleBatchSelect(evt) {
            evt.stopPropagation();
            evt.preventDefault();

            filesInfo = [];
            total = 0;

            let files = evt.target.files;
            setFilesInfo(files);

            let names = [];
            for (let i = 0; i < filesInfo.length; i++) {
                if (filesInfo[i].isFill()) {
                    names.push(filesInfo[i].name);
                }
            }

            $.ajax({
                url: "/ajax/batch_check_level/",
                type: "GET",
                data: {"data": names},
                traditional: true, 
                success: function(ret) {
                    if (ret.length == 0) {
                        for (let index = 0; index < filesInfo.length; index++) {
                            const info = filesInfo[index];
                            if (info.isFill()) {
                                total += 3;
                                checkImageSizeAndUpload(info.image, 'image', info);
                                uploadFile(info.ios, 'ios', info);
                                uploadFile(info.android, 'android', info);
                            }
                        }
                    } else {
                        let log = "";
                        for (let index = 0; index < ret.length; index++) {
                            log += ret[index] + ", ";
                        }
                        log = 'The following file names are repeated with others : ' + log + ' Please do NOT upload them use batch.';
                        alert(log);
                    }
                }
            });
        }

        function setFilesInfo(files) {
            for (let index = 0; index < files.length; index++) {
                const file = files[index];
                let pos = -1;
                if (file.name.includes('.jpg')) {
                    pos =  file.name.length - 4
                    let name = file.name.substring(0, pos);
                    let info = getFileInfo(name);
                    info.image = file;
                } else if((pos = file.name.lastIndexOf('a')) == file.name.length - 1) {
                    let name = file.name.substring(0, pos);
                    let info = getFileInfo(name);
                    info.android = file;
                } else if(file.name.includes('.meta') == false) {
                    let name = file.name;
                    let info = getFileInfo(name);
                    info.ios = file;
                }
            }
        }

        function getFileInfo(name) {
            for (let i = 0; i < filesInfo.length; i++) {
                const info = filesInfo[i];
                if (info.name == name) {
                    return info;
                }
            }
            const info = new Info(name);
            filesInfo.push(info);
            return filesInfo[filesInfo.length - 1];
        }

        function handleFileSelect(evt) {
            evt.stopPropagation();
            evt.preventDefault();

            let files = evt.target.files;
            if (files.length > 3) {
                alert('You need to choose less than 4 files!')
                return false;
            }

            for (let index = 0; index < files.length; index++) {
                const file = files[index];
                if (file.name.lastIndexOf('.jpg') != -1) {
                    if (checkNames(file.name, file.name.lastIndexOf('.jpg'))) {
                        checkImageSizeAndUpload(file, 'image');
                    }
                } else if (file.name.lastIndexOf('a') == file.name.length - 1) {
                    if (checkNames(file.name, file.name.length - 1)) {
                        uploadFile(file, 'android');
                    }
                } else if (file.name.lastIndexOf('.meta') == -1) {
                    if (checkNames(file.name, file.name.length)) {
                        uploadFile(file, 'ios');
                    }
                }
            }

            $('#id_name').val(old_name);
        }

        function checkNames(fullname, pos) {
            let name = fullname.substring(0, pos);
            if (old_name == '') {
                old_name = name;
            } else if (old_name != name) {
                alert('File name is wrong, please check it.')
                return false;
            }
            return true;
        }

        function checkImageSizeAndUpload(file, type, info) {
            let filename = file.name
            //创建读取文件的对象  
            let reader = new FileReader();
            //为文件读取成功设置事件  
            reader.onload = function (e) {
                let data = e.target.result;
                //加载图片获取图片真实宽度和高度  
                let image = new Image();
                image.onload = function () {
                    let imageSize = image.width + 'x' + image.height;
                    let requireSize = '1148x740';
                    image = null;
                    if (imageSize != requireSize) {
                        if (is_list_view) {
                            total--;
                        }
                        alert(filename + ' is NOT ' + requireSize + '.');
                    } else {
                        //上传图片
                        uploadFile(file, type, info);
                    }
                };
                image.src = data;
            };

            //正式读取文件  
            reader.readAsDataURL(file);
        }

        function uploadFile(file, type, info) {
            var metadata = {
                'contentType': file.type
            };

            $('#id_' + type).val('');
            storageRef.child('diff/levels/' + file.name).put(file, metadata).then(function (snapshot) {
                if (!is_list_view) {
                    $('#id_' + type).val(snapshot.downloadURL);
                    $('#id_' + type + '_md5').val(snapshot.metadata.md5Hash);
                } else {
                    if (type == 'image') {
                        info.image_url = snapshot.downloadURL;
                        info.image_md5 = snapshot.metadata.md5Hash;
                    } else if (type == 'ios') {
                        info.ios_url = snapshot.downloadURL;
                        info.ios_md5 = snapshot.metadata.md5Hash;
                    } else if (type == 'android') {
                        info.android_url = snapshot.downloadURL;
                        info.android_md5 = snapshot.metadata.md5Hash;
                    }

                    if (info.isUploadFill()) {
                        $.get("/ajax/upload_level/", {'name': info.name, 'image': info.image_url, 'ios': info.ios_url, 'android': info.android_url,
                            'ios_md5': info.ios_md5, 'android_md5': info.android_md5}, function (ret) {
                            count += 3;
                            $("#process").html('uploading: ' + count + '/' + total);
                            if (count == total) {
                                alert('Upload succeed.')
                                window.location.reload();
                            }
                        })
                    }
                }
            }).catch(function (error) {
                console.error('Upload failed:', error);
                alert('Upload failed.')
            });
        }
    }
})(django.jQuery);
